﻿using System;
using System.IO;
using System.Windows.Forms;
using Z2.Scripting;

namespace Z2.Editor
{
	public partial class ScriptEditor : Form
	{
		private readonly ScriptingEngine m_scriptingEngine;
		private World m_world;

		public ScriptEditor(World world)
		{
			InitializeComponent();
			this.Load += new EventHandler(ScriptEditor_Load);
			this.m_world = world;
			this.m_scriptingEngine = new ScriptingEngine();
			this.tbScript.AutoCompleteCustomSource = new AutoCompleteStringCollection();
			this.tbScript.AutoCompleteCustomSource.Add("class");
		}

		void ScriptEditor_Load(object sender, EventArgs e)
		{
			this.Load -= new EventHandler(ScriptEditor_Load);
			if (!string.IsNullOrEmpty(this.m_world.Script))
			{
				this.tbScript.Clear();
				this.tbScript.AppendText(this.m_world.Script);
			}
		}

		private void tsbLoadFromFile_Click(object sender, EventArgs e)
		{
			using (OpenFileDialog dialog = new OpenFileDialog())
			{
				dialog.Filter = "C# script|*.cs";
				if (dialog.ShowDialog() == DialogResult.OK)
				{
					using (FileStream stream = File.OpenRead(dialog.FileName))
					using(TextReader reader = new StreamReader(stream))
					{
						this.tbScript.Clear();
						this.tbScript.AppendText(reader.ReadToEnd());
					}
				}
			}
		}

		private void tsbTestCompile_Click(object sender, EventArgs e)
		{
			if (string.Compare(this.tbScript.Text, string.Empty) == 0) return;
			try
			{
				Guid id = this.m_scriptingEngine.AddScript(this.tbScript.Text);
				MessageBox.Show("Successfully compiled.", "Compile OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (ScriptingEngineException ex)
			{
				if (ex.IsCompileError)
				{
					Clipboard.SetText(ex.Message);
					MessageBox.Show(ex.Message, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else throw;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				this.m_scriptingEngine.Clear();
			}
		}

		private void btOK_Click(object sender, EventArgs e)
		{
			this.m_world.Script = this.tbScript.Text;
		}
	}
}
